<?php

namespace addons\qingdong\model;

use think\Exception;
use think\Model;
use think\Session;
use traits\model\SoftDelete;

/**
 *操作记录
 */
class OperationLog Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdong_operation_log';
	const   CUSTOMER_TYPE    = 1;//客户
	const   CONTACTS_TYPE    = 2;//联系人
	const   CONTRACT_TYPE    = 3;//合同
	const   LEADS_TYPE       = 4;//线索
	const   RECEIVABLES_TYPE = 5;//回款记录
    const   WORKORDER_TYPE = 6;//工单
    const   APPROVAL_TYPE = 7;//const
    const   BUSINESS_TYPE = 8;//商机
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';

	public function getCreatetimeAttr($value){
		return date('Y-m-d H:i',$value);
	}

	//获取跟进记录列表
	public static function getList($relation_type, $relation_id) {
		return self::where(['relation_type' => $relation_type, 'relation_id' => $relation_id])->with(['staff','admin'])->field('content,operation_id,createtime,operation_type')->order('id desc')->select();
	}


	//员工
	public function staff() {
		return $this->hasOne(Staff::class, 'id', 'operation_id')->removeOption('soft_delete')->field('id,name,img');
	}
    //员工
	public function admin() {
		return $this->hasOne(\app\admin\model\Admin::class, 'id', 'operation_id')->field('id,nickname');
	}


	//创建日志
	public static function createLog($relation_type, $relation_id, $content) {
		$staff = Staff::info();
		if(empty($staff)){
			$admin = Session::get('admin');
			$data  = [
				'content'        => $content,
				'operation_type' => 2,
				'operation_id'   => $admin['id']??0,
				'relation_type'  => $relation_type,
				'relation_id'    => $relation_id,
			];
		}else{
			$data  = [
				'content'        => $content,
				'operation_type' => 1,
				'operation_id'   => $staff->id,
				'relation_type'  => $relation_type,
				'relation_id'    => $relation_id,
			];
		}
		$Enent = new self;

		$result = $Enent->save($data);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Enent->getError());
		}

		return true;
	}
}
